@{
    ViewData["Title"] = "知识库管理";
}

<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex align-items-center">
                <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 60px; height: 60px;">
                    <i class="fas fa-book text-primary" style="font-size: 2rem;"></i>
                </div>
                <div>
                    <h2 class="mb-1 fw-bold">知识库管理</h2>
                    <p class="mb-0 text-muted">管理技术文档、操作手册和知识库内容</p>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- 知识库概览 -->
        <div class="col-lg-8">
            <div class="card border-0 shadow mb-4">
                <div class="card-header bg-light">
                    <h5 class="mb-0">
                        <i class="fas fa-chart-pie text-primary me-2"></i>知识库概览
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row text-center">
                        <div class="col-md-3 mb-3">
                            <div class="p-3">
                                <div class="bg-primary bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-2" style="width: 60px; height: 60px;">
                                    <i class="fas fa-file-alt text-primary" style="font-size: 1.5rem;"></i>
                                </div>
                                <h4 class="mb-1 fw-bold" id="totalDocuments">0</h4>
                                <small class="text-muted">总文档数</small>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="p-3">
                                <div class="bg-success bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-2" style="width: 60px; height: 60px;">
                                    <i class="fas fa-folder text-success" style="font-size: 1.5rem;"></i>
                                </div>
                                <h4 class="mb-1 fw-bold" id="totalCategories">0</h4>
                                <small class="text-muted">分类数量</small>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="p-3">
                                <div class="bg-info bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-2" style="width: 60px; height: 60px;">
                                    <i class="fas fa-search text-info" style="font-size: 1.5rem;"></i>
                                </div>
                                <h4 class="mb-1 fw-bold" id="totalSearches">0</h4>
                                <small class="text-muted">搜索次数</small>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="p-3">
                                <div class="bg-warning bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-2" style="width: 60px; height: 60px;">
                                    <i class="fas fa-clock text-warning" style="font-size: 1.5rem;"></i>
                                </div>
                                <h4 class="mb-1 fw-bold" id="lastUpdated">-</h4>
                                <small class="text-muted">最后更新</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 知识库操作 -->
            <div class="card border-0 shadow mb-4">
                <div class="card-header bg-light">
                    <h5 class="mb-0">
                        <i class="fas fa-cogs text-success me-2"></i>知识库操作
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <div class="d-grid">
                                <button class="btn btn-primary btn-lg" id="initializeKnowledgeBase">
                                    <i class="fas fa-magic me-2"></i>初始化知识库
                                </button>
                                <small class="text-muted mt-1">首次使用或重置知识库时使用</small>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="d-grid">
                                <button class="btn btn-success btn-lg" data-bs-toggle="modal" data-bs-target="#addDocumentModal">
                                    <i class="fas fa-plus me-2"></i>添加文档
                                </button>
                                <small class="text-muted mt-1">添加新的技术文档或操作手册</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 文档列表 -->
            <div class="card border-0 shadow">
                <div class="card-header bg-light">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">
                            <i class="fas fa-list text-info me-2"></i>文档列表
                        </h5>
                        <div class="input-group" style="width: 300px;">
                            <input type="text" class="form-control" id="searchInput" placeholder="搜索文档...">
                            <button class="btn btn-outline-secondary" type="button" id="searchButton">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div id="documentList" class="list-group list-group-flush">
                        <div class="list-group-item text-center text-muted py-4">
                            <i class="fas fa-inbox fa-2x mb-2"></i>
                            <p class="mb-0">暂无文档，请先初始化知识库或添加文档</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 侧边栏 -->
        <div class="col-lg-4">
            <!-- 知识库状态 -->
            <div class="card border-0 shadow mb-4">
                <div class="card-header bg-light">
                    <h6 class="mb-0">
                        <i class="fas fa-server text-success me-2"></i>系统状态
                    </h6>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span>向量数据库</span>
                        <span class="badge bg-success" id="vectorDbStatus">正常</span>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span>AI模型</span>
                        <span class="badge bg-success" id="aiModelStatus">正常</span>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span>索引状态</span>
                        <span class="badge bg-success" id="indexStatus">已建立</span>
                    </div>
                    <div class="d-flex justify-content-between align-items-center">
                        <span>同步状态</span>
                        <span class="badge bg-success" id="syncStatus">已同步</span>
                    </div>
                </div>
            </div>

            <!-- 快速统计 -->
            <div class="card border-0 shadow mb-4">
                <div class="card-header bg-light">
                    <h6 class="mb-0">
                        <i class="fas fa-chart-bar text-warning me-2"></i>快速统计
                    </6>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label small text-muted">文档类型分布</label>
                        <div class="progress mb-2" style="height: 8px;">
                            <div class="progress-bar bg-primary" style="width: 40%"></div>
                        </div>
                        <small class="text-muted">操作手册 40%</small>
                    </div>
                    <div class="mb-3">
                        <div class="progress mb-2" style="height: 8px;">
                            <div class="progress-bar bg-success" style="width: 30%"></div>
                        </div>
                        <small class="text-muted">技术文档 30%</small>
                    </div>
                    <div class="mb-3">
                        <div class="progress mb-2" style="height: 8px;">
                            <div class="progress-bar bg-info" style="width: 20%"></div>
                        </div>
                        <small class="text-muted">故障排除 20%</small>
                    </div>
                    <div class="mb-3">
                        <div class="progress mb-2" style="height: 8px;">
                            <div class="progress-bar bg-warning" style="width: 10%"></div>
                        </div>
                        <small class="text-muted">其他 10%</small>
                    </div>
                </div>
            </div>

            <!-- 最近活动 -->
            <div class="card border-0 shadow">
                <div class="card-header bg-light">
                    <h6 class="mb-0">
                        <i class="fas fa-history text-info me-2"></i>最近活动
                    </6>
                </div>
                <div class="card-body">
                    <div id="recentActivities">
                        <div class="d-flex align-items-center mb-2">
                            <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 30px; height: 30px;">
                                <i class="fas fa-plus text-primary fa-sm"></i>
                            </div>
                            <div class="flex-grow-1">
                                <small class="fw-bold">知识库初始化</small>
                                <br><small class="text-muted">刚刚</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加文档模态框 -->
<div class="modal fade" id="addDocumentModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-plus text-success me-2"></i>添加知识库文档
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addDocumentForm">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="documentTitle" class="form-label">文档标题 *</label>
                            <input type="text" class="form-control" id="documentTitle" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="documentCategory" class="form-label">文档分类 *</label>
                            <select class="form-select" id="documentCategory" required>
                                <option value="">请选择分类</option>
                                <option value="操作手册">操作手册</option>
                                <option value="技术文档">技术文档</option>
                                <option value="故障排除">故障排除</option>
                                <option value="安全规范">安全规范</option>
                                <option value="其他">其他</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="documentContent" class="form-label">文档内容 *</label>
                        <textarea class="form-control" id="documentContent" rows="8" required 
                                  placeholder="请输入文档内容，支持Markdown格式..."></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="documentTags" class="form-label">标签</label>
                            <input type="text" class="form-control" id="documentTags" 
                                   placeholder="用逗号分隔多个标签">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="documentAuthor" class="form-label">作者</label>
                            <input type="text" class="form-control" id="documentAuthor" 
                                   placeholder="文档作者">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="documentDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="documentDescription" rows="3" 
                                  placeholder="文档的简要描述..."></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-success" id="submitDocument">
                    <i class="fas fa-save me-1"></i>保存文档
                </button>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        $(document).ready(function() {
            // 初始化知识库
            $('#initializeKnowledgeBase').click(function() {
                if (confirm('确定要初始化知识库吗？这将清空所有现有数据。')) {
                    initializeKnowledgeBase();
                }
            });

            // 添加文档
            $('#submitDocument').click(function() {
                submitDocument();
            });

            // 搜索文档
            $('#searchButton').click(function() {
                searchDocuments();
            });

            $('#searchInput').keypress(function(e) {
                if (e.which == 13) {
                    searchDocuments();
                }
            });

            // 加载初始数据
            loadKnowledgeBaseStats();
        });

        function initializeKnowledgeBase() {
            const button = $('#initializeKnowledgeBase');
            const originalText = button.html();
            
            button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-2"></i>初始化中...');
            
            $.ajax({
                url: '@Url.Action("InitializeKnowledgeBase", "Chat")',
                type: 'POST',
                success: function(response) {
                    if (response.success) {
                        showAlert('success', '知识库初始化成功！');
                        loadKnowledgeBaseStats();
                        updateRecentActivities('知识库初始化', 'success');
                    } else {
                        showAlert('danger', '知识库初始化失败：' + response.message);
                    }
                },
                error: function() {
                    showAlert('danger', '知识库初始化失败，请检查网络连接');
                },
                complete: function() {
                    button.prop('disabled', false).html(originalText);
                }
            });
        }

        function submitDocument() {
            const form = $('#addDocumentForm')[0];
            if (!form.checkValidity()) {
                form.reportValidity();
                return;
            }

            const documentData = {
                document: $('#documentContent').val(),
                metadata: {
                    title: $('#documentTitle').val(),
                    category: $('#documentCategory').val(),
                    tags: $('#documentTags').val().split(',').map(tag => tag.trim()).filter(tag => tag),
                    author: $('#documentAuthor').val(),
                    description: $('#documentDescription').val(),
                    createdAt: new Date().toISOString()
                }
            };

            const button = $('#submitDocument');
            const originalText = button.html();
            
            button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>保存中...');
            
            $.ajax({
                url: '@Url.Action("AddKnowledgeDocument", "Chat")',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(documentData),
                success: function(response) {
                    if (response.success) {
                        showAlert('success', '文档添加成功！');
                        $('#addDocumentModal').modal('hide');
                        $('#addDocumentForm')[0].reset();
                        loadKnowledgeBaseStats();
                        updateRecentActivities('添加文档：' + documentData.metadata.title, 'success');
                    } else {
                        showAlert('danger', '文档添加失败：' + response.message);
                    }
                },
                error: function() {
                    showAlert('danger', '文档添加失败，请检查网络连接');
                },
                complete: function() {
                    button.prop('disabled', false).html(originalText);
                }
            });
        }

        function searchDocuments() {
            const query = $('#searchInput').val().trim();
            if (!query) return;

            // 这里可以实现文档搜索功能
            showAlert('info', '搜索功能开发中，搜索词：' + query);
        }

        function loadKnowledgeBaseStats() {
            // 模拟加载统计数据
            $('#totalDocuments').text('12');
            $('#totalCategories').text('5');
            $('#totalSearches').text('156');
            $('#lastUpdated').text('刚刚');
        }

        function updateRecentActivities(action, type) {
            const iconClass = type === 'success' ? 'fa-check text-success' : 'fa-info text-info';
            const time = '刚刚';
            
            const activityHtml = `
                <div class="d-flex align-items-center mb-2">
                    <div class="bg-${type === 'success' ? 'success' : 'info'} bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 30px; height: 30px;">
                        <i class="fas ${iconClass} fa-sm"></i>
                    </div>
                    <div class="flex-grow-1">
                        <small class="fw-bold">${action}</small>
                        <br><small class="text-muted">${time}</small>
                    </div>
                </div>
            `;
            
            $('#recentActivities').prepend(activityHtml);
        }

        function showAlert(type, message) {
            const alertHtml = `
                <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            
            // 在页面顶部显示提示
            $('.container-fluid').prepend(alertHtml);
            
            // 3秒后自动消失
            setTimeout(function() {
                $('.alert').fadeOut();
            }, 3000);
        }
    </script>
}

<style>
.card {
    transition: transform 0.2s ease-in-out;
}

.card:hover {
    transform: translateY(-2px);
}

.bg-primary {
    background-color: #667eea !important;
}

.btn-primary {
    background-color: #667eea;
    border-color: #667eea;
}

.btn-primary:hover {
    background-color: #5a6fd8;
    border-color: #5a6fd8;
}

.progress {
    border-radius: 10px;
}

.progress-bar {
    border-radius: 10px;
}

.list-group-item {
    transition: background-color 0.2s ease-in-out;
}

.list-group-item:hover {
    background-color: #f8f9fa;
}

.modal-header {
    background-color: #f8f9fa;
    border-bottom: 1px solid #dee2e6;
}

.alert {
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 9999;
    min-width: 300px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
</style> 